<script setup>
import { getCurrentInstance, ref } from "vue";
import Pagination from "@/components/Pagination/index.vue";
import {
	addTrainCertificate,
	delTrainCertificate,
	editTrainCertificate,
	getTrainCertificateDetailsByKey,
	getTrainCertificatePage,
} from "@/api/company/certificate";
import { getToken } from "@/utils/auth";

const { proxy } = getCurrentInstance();

const queryParams = ref({
	pageNum: 1,
	pageSize: 10,
	// 证书名称
	certificateName: "",
	// 证书编号
	certificateCode: "",
	// 培训人姓名
	name: "",
});

const loading = ref(false);

const getTableData = async (params) => {
	loading.value = true;
	const res = await getTrainCertificatePage({
		...params,
	});
	try {
		if (res.code === 200) {
			tableData.value = res.data.records;
			total.value = res.data.total;
		}
	} catch (e) {
		proxy.$modal.msgError(JSON.stringify(e));
	} finally {
		loading.value = false;
	}
};

const search = async () => {
	// TODO 搜索
	queryParams.value.pageNum = 1;
	await getTableData(queryParams.value);
};

const addCertificate = () => {
	// TODO 添加培训证书
	rowId.value = null;
	editVisible.value = true;
};

const total = ref(0);
const rowId = ref(null);
const tableData = ref([]);

const handleUpdate = (row) => {
	editVisible.value = true;
	rowId.value = row.id;
};
const handleDelete = (row) => {
	// TODO 删除
	proxy.$modal
		.confirm('是否确认删除名称为"' + row.certificateName + '"的数据项?')
		.then(function () {
			return delTrainCertificate(row.id);
		})
		.then(() => {
			getTableData(queryParams.value);
			proxy.$modal.msgSuccess("删除成功");
		})
		.catch(() => {});
};
const imageList = ref([]);
const onOpen = async () => {
	if (rowId.value) {
		imageList.value = [];
		const res = await getTrainCertificateDetailsByKey({ id: rowId.value });
		try {
			if (res.code === 200) {
				formData.value = res.data;
				formData.value.fileUrl = res.data.files[0].accessUrl;
				formData.value.fileIds = res.data.files[0].id;
			} else {
			}
		} catch (e) {
			console.log(e);
		}
	} else {
		formData.value.fileIds = [];
		formData.fileUrl = null;
		console.log(formData.fileUrl, "rowId.value");
	}
};
const onClose = async () => {
	proxy.resetForm("elForm");
	rowId.value = null;
	clearFile();
};

const fileAction = import.meta.env.VITE_APP_BASE_API + "/trainCertificate/file";
const photoBeforeUpload = (file) => {
	let isRightSize = file.size / 1024 / 1024 < 20;
	if (!isRightSize) {
		proxy.$modal.msgError("文件大小超过 20MB");
	}
	return isRightSize;
};

const editVisible = ref(false);
const formData = ref({
	// id
	id: null,
	// 证书编号
	certificateCode: "",
	// 证书名称
	certificateName: "",
	// 照片
	fileIds: [],
	fileUrl: null,
	// 身份证号
	identityCard: "",
	// 培训人姓名
	name: "",
	// 简述
	remark: "",
});
const rules = {
	certificateName: [
		{
			required: true,
			message: "请输入证书名称",
			trigger: "blur",
		},
	],
	name: [
		{
			required: true,
			message: "请输入培训人姓名",
			trigger: "blur",
		},
	],
	certificateCode: [
		{
			required: true,
			message: "请输入证书编号",
			trigger: "blur",
		},
	],
	identityCard: [
		{
			required: true,
			message: "请输入身份证号",
			trigger: "blur",
		},
	],
	fileIds: [
		{
			required: true,
			message: "请上传照片",
			trigger: "blur",
		},
	],
};
const clearFile = () => {
	formData.value.fileUrl = null;
	formData.value.fileIds = [];
	proxy.$refs["fileIds"].clearFiles();
};
const handleRemove = (file, fileList) => {
	formData.value.fileUrl = null;
	formData.value.fileIds = [];
};
const uploadSuccess = (response, file, fileList) => {
	if (response.code === 200) {
		formData.value.fileIds = response.data.id;
		formData.value.fileUrl = response.data.accessUrl;
	} else {
		formData.value.fileIds = [];
		formData.value.fileUrl = null;
	}
};
const submitForm = async () => {
	proxy.$refs["elForm"].validate(async (valid) => {
		if (valid) {
			console.log(formData.value.fileIds);
			const params = {
				...formData.value,
			};
			params["fileIds"] = [params.fileIds];
			console.log(params);
			let res;
			if (rowId.value) {
				res = await editTrainCertificate(params);
			} else {
				delete params.id;
				res = await addTrainCertificate(params);
			}
			try {
				proxy.$modal.msgSuccess(res.msg);
				// console.log(res);
				cancel("submit");
			} catch (e) {
				proxy.$modal.msgError(JSON.stringify(e));
			}
		}
	});
};
const cancel = (type = "cancel") => {
	proxy.resetForm("elForm");
	rowId.value = null;
	editVisible.value = false;
	if (type === "submit") {
		search();
	}
};

search();
</script>

<template>
	<div class="app-container">
		<el-form ref="queryForm" :model="queryParams" inline label-width="100px" @submit.native.prevent>
			<el-form-item label="证书名称" prop="certificateName">
				<el-input :style="{ width: '200px' }" clearable placeholder="请输入证书名称" v-model="queryParams.certificateName"></el-input>
			</el-form-item>
			<el-form-item label="培训人姓名" prop="name">
				<el-input :style="{ width: '200px' }" clearable placeholder="请输入培训人姓名" v-model="queryParams.name"></el-input>
			</el-form-item>
			<el-form-item label="证书编号" prop="certificateCode">
				<el-input :style="{ width: '200px' }" clearable placeholder="请输入证书编号" v-model="queryParams.certificateCode"></el-input>
			</el-form-item>
			<el-form-item>
				<el-button :disabled="loading" icon="Search" type="primary" @click="search">搜索 </el-button>
				<el-button :disabled="loading" type="primary" @click="addCertificate">添加培训证书 </el-button>
			</el-form-item>
		</el-form>
		<el-table v-loading="loading" :data="tableData">
			<el-table-column :show-overflow-tooltip="true" label="证书名称" prop="certificateName" />
			<el-table-column :show-overflow-tooltip="true" label="培训人姓名" prop="name" width="140" />
			<el-table-column :show-overflow-tooltip="true" label="身份证号码" prop="identityCard" width="240" />
			<el-table-column :show-overflow-tooltip="true" label="证书编号" prop="certificateCode" width="240" />
			<el-table-column :show-overflow-tooltip="true" label="添加时间" prop="createTime" width="160" />
			<el-table-column align="center" class-name="small-padding fixed-width" label="操作" width="160">
				<template #default="scope">
					<el-button icon="Edit" link type="primary" @click="handleUpdate(scope.row)">编辑</el-button>
					<el-button icon="Delete" link type="danger" @click="handleDelete(scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>
		<pagination
			v-show="total > 0"
			:total="total"
			v-model:page="queryParams.pageNum"
			v-model:limit="queryParams.pageSize"
			@pagination="search"></pagination>

		<el-dialog
			:title="rowId ? '修改培训证书' : '添加培训证书'"
			v-model="editVisible"
			append-to-body
			destroy-on-close
			center
			@open="onOpen"
			@close="onClose">
			<el-form ref="elForm" :model="formData" label-width="100px" :rules="rules">
				<el-form-item label="证书名称" prop="certificateName">
					<el-input v-model="formData.certificateName" :style="{ width: '100%' }" clearable placeholder="请输入证书名称"></el-input>
				</el-form-item>
				<el-form-item label="培训人姓名" prop="name">
					<el-input v-model="formData.name" :style="{ width: '100%' }" clearable placeholder="请输入培训人姓名"></el-input>
				</el-form-item>
				<el-form-item label="身份证号码" prop="identityCard">
					<el-input v-model="formData.identityCard" :style="{ width: '100%' }" clearable placeholder="请输入身份证号码"></el-input>
				</el-form-item>
				<el-form-item label="证书编号" prop="certificateCode">
					<el-input v-model="formData.certificateCode" :style="{ width: '100%' }" clearable placeholder="请输入证书编号"></el-input>
				</el-form-item>
				<el-form-item label="证书照片" prop="fileIds" required>
					<el-upload
						ref="fileIds"
						:accept="'.jpg,.jpeg,.png'"
						:action="fileAction"
						:before-upload="photoBeforeUpload"
						:headers="{
							Authorization: 'Bearer ' + getToken(),
						}"
						:limit="1"
						:list-type="'picture'"
						:on-remove="handleRemove"
						:on-success="uploadSuccess"
						:file-list="imageList"
						:show-file-list="false">
						<el-button :disabled="formData.fileUrl" icon="Upload" :size="'small'" type="primary">点击上传 </el-button>
						<el-button size="small" type="warning" @click.stop="clearFile">清空上传</el-button>
					</el-upload>
				</el-form-item>
				<el-form-item v-if="formData.fileUrl !== null && formData.fileUrl !== ''" prop="fileUrl">
					<el-image :preview-src-list="[formData.fileUrl]" :src="formData.fileUrl" style="width: 100px; height: 100px"> </el-image>
				</el-form-item>
				<el-form-item label="简述" prop="remark">
					<el-input v-model="formData.remark" :autosize="{ minRows: 4, maxRows: 4 }" type="textarea" placeholder="请输入简述"></el-input>
				</el-form-item>
			</el-form>
			<template #footer>
				<div class="dialog-footer">
					<el-button type="primary" @click="submitForm">提交</el-button>
					<el-button @click="cancel('cancel')">取消</el-button>
				</div>
			</template>
		</el-dialog>
	</div>
</template>

<style lang="scss" scoped></style>
